package com.longway.common.controller;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import com.longway.common.kit.JStrKit;
import com.longway.common.model.BaseMenu;
import com.longway.common.model.BaseUser;
import com.longway.common.service.BusinessService;
import com.longway.core.toolbox.Func;
import com.longway.core.toolbox.support.SqlKeyword;
import java.util.List;
import java.util.Map;

public class CacheController extends BaseController{

	public void index() {

	}

	/**
	 * 获取按钮组
	 */
	public void getBtn() {
		final String code = getPara("code");
		BaseUser user =super.getLoginAccount();
		final Long userId = user.getId();
		final  String roleId = user.getRoleId();

		Record userRole = CacheKit.get(MENU_CACHE, "roleExt_" + userId,
				new IDataLoader() {
					@Override
					public Record load() {
						return Db.findFirst("select * from base_role_ext where userId= ?", userId);
					}
				});

		String roleIn = "0";
		String roleOut = "0";
		if (userRole != null) {
			roleIn = userRole.getStr("roleIn");
			roleOut = userRole.getStr("roleOut");
		}
		final StringBuilder sql = new StringBuilder();
		sql.append("select base_menu.* ,(select name from base_menu where code=?) as pname  from base_menu");
		sql.append(" where ( ");
		sql.append("	 (status=1 or status=2)");
		sql.append("	 and (icon is not null and (icon like '%btn%' or icon like '%icon%' ) ) ");
		sql.append("	 and (pCode=?)");
		sql.append("	 and (id in (select menuId from base_relation where roleId in (?)) or id in ("+roleIn+"))");
		sql.append("	 and id not in("+roleOut+")");
		sql.append("	)");
		sql.append(" order by num");

		List<Record> btnList = CacheKit.get(MENU_CACHE, "btnList_" + code + "_"
				+ userId, new IDataLoader() {
			@Override
			public List<Record> load() {
				return Db.find(sql.toString(), code,code,roleId);
			}
		});
		renderJson(ajaxSucess(btnList));
	}

	/**
	 * 获取按钮组
	 */
	public void getChildBtn() {
		final String code = getPara("code");
		BaseUser user =super.getLoginAccount();
		final Long userId = user.getId();
		final String roleId = user.getRoleId();

		Record userRole = CacheKit.get(MENU_CACHE, "roleExt_" + userId,
				new IDataLoader() {
					@Override
					public Record load() {
						return Db.findFirst("select * from base_role_ext where userId= ?", userId);
					}
				});

		String roleIn = "0";
		String roleOut = "0";
		if (!Func.isEmpty(userRole)) {
			roleIn = userRole.getStr("roleIn");
			roleOut = userRole.getStr("roleOut");
		}
		final StringBuilder sql = new StringBuilder();
		sql.append("select base_menu.* ,(select name from base_menu where code=?) as pname  from base_menu");
		sql.append(" where ( ");
		sql.append("	 (status=1 or status = 2)");
		sql.append("	 and (icon is not null and (icon like '%btn%' or icon like '%icon%' ) ) ");
		sql.append("	 and (pCode=?)");
		sql.append("	 and (id in (select menuId from base_relation where roleId in ("
				+ roleId + ")) or id in (" + roleIn + "))");
		sql.append("	 and id not in(" + roleOut + ")");
		sql.append("	)");
		sql.append(" order by num");


		List<Record>  btnList = CacheKit.get(MENU_CACHE, "childBtnList_" + code + "_" + userId, new IDataLoader() {
			@Override
			public List<Record> load() {
				return Db.find(sql.toString(), code,code);
			}
		});
		renderJson(ajaxSucess(btnList));
	}

	/**
	 * 根据字典编号获取下拉框
	 *
	 * @return String
	 */
	public void getSelect() {
		final String code = getPara("code");
		final String num = getPara("num");
		String id = getPara("id")==null?"":getPara("id");
		id = " _"+id+"_inputs"+num;
		List<Record> dict = CacheKit.get(DICT_CACHE, "dict_common_" + code,
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select num as id,pid as pid,name as text from  base_dict where code=? and num>=0 order by xssx",code);
					}
				});
		StringBuilder sb = new StringBuilder();
		sb.append("<select class=\"form-control\" style=\"margin-left:-3px;cursor:pointer;\" id="+id+" >");
		sb.append("<option value></option>");
		for (Record dic : dict) {
			sb.append("<option value=\"" + dic.get("id") + "\">" + dic.get("text") + "</option>");
		}
		sb.append("</select>");
		renderJson(ajaxSucess(sb.toString()));
	}
	
	public void getSelectById() {
		final String code = getPara("code");
		String id = getPara("id")==null?"":getPara("id");
		List<Record> dict = CacheKit.get(DICT_CACHE, "dict_common_" + code,
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select num as id,pid as pid,name as text from  base_dict where code=? and num>=0 order by xssx",code);
					}
				});
		StringBuilder sb = new StringBuilder();
		sb.append("<select class=\"form-control\" style=\"margin-left:-3px;cursor:pointer;\" id="+id+" >");
		sb.append("<option value></option>");
		for (Record dic : dict) {
			sb.append("<option tail=\"" + dic.get("text") + "\"  value=\"" + dic.get("id") + "\">" + dic.get("text") + "</option>");
		}
		sb.append("</select>");
		renderJson(ajaxSucess(sb.toString()));
	}

	public void getCombo() {
		final String code = getPara("code");
		List<Record> dict = CacheKit.get(DICT_CACHE, "dict_combo_" + code,
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select num as \"id\",name as \"text\" from  base_dict where code=? and num>=0 order by xssx", code);
					}
				});

		renderJson(ajaxSucess(dict));;
	}

	public void getDeptSelect() {
		final String num = getPara("num");
		String id = getPara("id")==null?"":getPara("id");
		id = "_"+id+"_inputs"+num;
		List<Record> dept = CacheKit.get(DEPT_CACHE, "dept_all",
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select id,pid,simpleName as text from  base_dept order by pid,num asc");
					}
				});
		StringBuilder sb = new StringBuilder();
		sb.append("<select class=\"form-control\" style=\"margin-left:-3px;cursor:pointer;\" id="+id+" >");
		sb.append("<option value></option>");
		for (Record _dept : dept) {
			sb.append("<option value=\"" + _dept.get("id") + "\">" + _dept.get("text") + "</option>");
		}
		sb.append("</select>");
		renderJson(ajaxSucess(sb.toString()));
	}
	
	public void getDeptSelectById() {
		String id = getPara("id")==null?"":getPara("id");
		List<Record> dept = CacheKit.get(DEPT_CACHE, "dept_all",
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select id,pid,simpleName as text from  base_dept order by pid,num asc");
					}
				});
		StringBuilder sb = new StringBuilder();
		sb.append("<select class=\"form-control\" style=\"margin-left:-3px;cursor:pointer;\" id="+id+" >");
		sb.append("<option value></option>");
		for (Record _dept : dept) {
			sb.append("<option value=\"" + _dept.get("id") + "\">" + _dept.get("text") + "</option>");
		}
		sb.append("</select>");
		renderJson(ajaxSucess(sb.toString()));
	}

	/**
	 * 搜索框展示所有企业
	 */
	public void getQyglSelectById() {
		String id = getPara("id")==null?"":getPara("id");
		String roleId = getLoginAccount().getRoleId();
		String sql = "select qymc as text,id from lhyg_qygl order by createTime desc";
		if (INTERCEPT_ROLE_ID.get(roleId) != null) {
			sql = "select qymc as text,id from lhyg_qygl where createById = " + getLoginAccountId() + " order by createTime desc";
		}
		String finalSql = sql;
		List<Record> dept = Db.find(finalSql);
//		List<Record> dept = CacheKit.get(DEPT_CACHE, "dept_all",
//				new IDataLoader() {
//					@Override
//					public List<Record> load() {
//						return Db.find(finalSql);
//					}
//				});
		StringBuilder sb = new StringBuilder();
		sb.append("<select class=\"form-control\" style=\"margin-left:-3px;cursor:pointer;\" id="+id+" >");
		sb.append("<option value></option>");
		for (Record _dept : dept) {
			sb.append("<option value=\"" + _dept.get("id") + "\">" + _dept.get("text") + "</option>");
		}
		sb.append("</select>");
		renderJson(ajaxSucess(sb.toString()));
	}

	/**
	 * 搜索框只展示发放过佣金的企业
	 */
	public void getFfQyglSelectById() {
		String id = getPara("id")==null?"":getPara("id");
		String roleId = getLoginAccount().getRoleId();
		String sql = "select qygl.qymc text,qygl.id id from lhyg_qygl qygl inner join lhyg_ffjl ffjl on ffjl.qyId = qygl.id group by qygl.id order by qygl.createTime desc";
		if (INTERCEPT_ROLE_ID.get(roleId) != null) {
			sql = "select qygl.qymc text,qygl.id id from lhyg_qygl qygl inner join lhyg_ffjl ffjl on ffjl.qyId = qygl.id where qygl.createById = " + getLoginAccountId() + " group by qygl.id order by qygl.createTime desc";
		}
		String finalSql = sql;
		List<Record> dept = Db.find(finalSql);
		StringBuilder sb = new StringBuilder();
		sb.append("<select class=\"form-control\" style=\"margin-left:-3px;cursor:pointer;\" id="+id+" >");
		sb.append("<option value></option>");
		for (Record _dept : dept) {
			sb.append("<option value=\"" + _dept.get("id") + "\">" + _dept.get("text") + "</option>");
		}
		sb.append("</select>");
		renderJson(ajaxSucess(sb.toString()));
	}

	/**
	 * 搜索框只展示可开票的企业
	 */
	public void getTaxQyglSelectById() {
		String id = getPara("id")==null?"":getPara("id");
		String roleId = getLoginAccount().getRoleId();
		String sql = "select qygl.qymc text,qygl.id id from lhyg_qygl qygl inner join lhyg_ffjl ffjl on ffjl.qyId = qygl.id where ffjl.state in (3,4) and ffjl.rate < 5 group by qygl.id order by qygl.createTime desc";
		if (INTERCEPT_ROLE_ID.get(roleId) != null) {
			sql = "select qygl.qymc text,qygl.id id from lhyg_qygl qygl inner join lhyg_ffjl ffjl on ffjl.qyId = qygl.id where ffjl.state in (3,4) and ffjl.rate < 5 and qygl.createById = " + getLoginAccountId() + " group by qygl.id order by qygl.createTime desc";
		}
		String finalSql = sql;
		List<Record> dept = Db.find(finalSql);
		StringBuilder sb = new StringBuilder();
		sb.append("<select class=\"form-control\" style=\"margin-left:-3px;cursor:pointer;\" id="+id+" >");
		sb.append("<option value></option>");
		for (Record _dept : dept) {
			sb.append("<option value=\"" + _dept.get("id") + "\">" + _dept.get("text") + "</option>");
		}
		sb.append("</select>");
		renderJson(ajaxSucess(sb.toString()));
	}


	public void getUserSelect() {
		final String num = getPara("num");
		String id = getPara("id")==null?"":getPara("id");
		id = "_"+id+"_inputs"+num;
		List<Record> dept = CacheKit.get(DEPT_CACHE, "user_all",
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select id,name text from base_user where status=2 and name is not null order by name");
					}
				});
		StringBuilder sb = new StringBuilder();
		sb.append("<select class=\"form-control\" style=\"margin-left:-3px;cursor:pointer;\" id="+id+" >");
		sb.append("<option value></option>");
		for (Record _dept : dept) {
			sb.append("<option value=\"" + _dept.get("id") + "\">" + _dept.get("text") + "</option>");
		}
		sb.append("</select>");
		renderJson(ajaxSucess(sb.toString()));
	}
	
	public void getUserSelectById() {
		String id = getPara("id")==null?"":getPara("id");
		List<Record> dept = CacheKit.get(DEPT_CACHE, "user_all",
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select id,name text from base_user where status=2 and name is not null order by name");
					}
				});
		StringBuilder sb = new StringBuilder();
		sb.append("<select class=\"form-control\" style=\"margin-left:-3px;cursor:pointer;\" id="+id+" >");
		sb.append("<option value></option>");
		for (Record _dept : dept) {
			sb.append("<option value=\"" + _dept.get("id") + "\">" + _dept.get("text") + "</option>");
		}
		sb.append("</select>");
		renderJson(ajaxSucess(sb.toString()));
	}

	public void getRoleSelect() {
		final String num = getPara("num");
		String id = getPara("id")==null?"":getPara("id");
		id = "_"+id+"_inputs"+num;
		List<Record> dept = CacheKit.get(ROLE_CACHE, "role_all",
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select id,name text from base_role where  name is not null order by name ");
					}
				});
		StringBuilder sb = new StringBuilder();
		sb.append("<select class=\"form-control\" style=\"margin-left:-3px;cursor:pointer;\" id="+id+" >");
		sb.append("<option value></option>");
		for (Record _dept : dept) {
			sb.append("<option value=\"" + _dept.get("id") + "\">" + _dept.get("text") + "</option>");
		}
		sb.append("</select>");
		renderJson(ajaxSucess(sb.toString()));
	}
	
	public void getRoleSelectById() {
		String id = getPara("id")==null?"":getPara("id");
		List<Record> dept = CacheKit.get(ROLE_CACHE, "role_all",
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select id,name text from base_role where  name is not null order by name ");
					}
				});
		StringBuilder sb = new StringBuilder();
		sb.append("<select class=\"form-control\" style=\"margin-left:-3px;cursor:pointer;\" id="+id+" >");
		sb.append("<option value></option>");
		for (Record _dept : dept) {
			sb.append("<option value=\"" + _dept.get("id") + "\">" + _dept.get("text") + "</option>");
		}
		sb.append("</select>");
		renderJson(ajaxSucess(sb.toString()));
	}

	/*public void getCitySelectByPid() {
		String pid = getPara();
		List<Record> citys = CacheKit.get(DICT_CACHE, "city_"+pid,
				new IDataLoader() {
					public List<Record> load() {
						return Db.find("select CONCAT(id,'') as id,areaCode as code,areaName as name from base_city where pid= "+pid+" order by num");
					}
				});
		renderJson(ajaxSucess(citys));
	}

	public void getCitySelectByCode() {
		String code = getPara();
		String pid = Db.queryStr("select pid from base_city where areaCode = ? ", code);
		List<Record> citys = CacheKit.get(DICT_CACHE, "city_"+pid,
				new IDataLoader() {
					public List<Record> load() {
						return Db.find("select CONCAT(id,'') as id,areaCode as code,areaName as name from base_city where pid= "+pid+" order by num");
					}
				});
		renderJson(ajaxSucess(citys));
	}*/

	public void dicTreeList() {
		List<Record> dic = CacheKit.get(DICT_CACHE, "dict_all",
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select code \"code\",id \"id\",pid \"pId\",name \"name\",num \"num\",'false' \"open\" from base_dict order by code asc,xssx asc");
					}
				});

		renderJson(ajaxSucess(dic));
	}

	/*public void dicTreeListByCode() {
		String code = getPara();
		List<Record> dic = CacheKit.get(DICT_CACHE, "dict_"+code,
				new IDataLoader() {
					public List<Record> load() {
						return Db.find("select code \"code\",id \"id\",pid \"pId\",name \"name\",num \"num\" from base_dict where code= "+code+" order by code asc,num asc");
					}
				});
		renderJson(ajaxSucess(dic));
	}*/

	/*public void dicTreeListByPid() {
		String pid = getPara();
		List<Record> dic = CacheKit.get(DICT_CACHE, "dict_"+pid,
				new IDataLoader() {
					public List<Record> load() {
						return Db.find("select code \"code\",id \"id\",pid \"pId\",name \"name\",num \"num\" from base_dict where pid= "+pid+" order by code asc,num asc");
					}
				});

		renderJson(ajaxSucess(dic));
	}*/

	public void deptTreeList() {
		BaseUser user =super.getLoginAccount();
		Long userId = user.getId();
		List<Record> dept = CacheKit.get(DEPT_CACHE, "dept_tree_all_" + userId,
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select id \"id\",pid \"pId\",simpleName as \"name\",(case when (pid=0 or pid is null) then 'true' else 'false' end) \"open\" from  base_dept order by num");
					}
				});

		renderJson(ajaxSucess(dept));
	}

	/*public void deptTreeListById() {
//		BaseUser user =super.getLoginAccount();
		Long deptId = getLoginAccount().getDeptid();
		BaseDept deptDao = DeptService.me.findById(deptId);
		List<Record> dept = CacheKit.get(DEPT_CACHE, "dept_tree_all_" + deptId,
				new IDataLoader() {
					public List<Record> load() {
						List<Record> find = Db.find("select id \"id\",pid \"pId\",simpleName as \"name\",('false') \"open\" from  base_dept where leftCode >= ? and rightCode <=? ORDER BY num asc",deptDao.getLeftcode(),deptDao.getRightcode());
						return find;
					}
				});

		renderJson(ajaxSucess(dept));
	}*/

	public void roleTreeList() {
		BaseUser user =super.getLoginAccount();
		Long userId = user.getId();
		List<Record> dept = CacheKit.get(ROLE_CACHE, "role_tree_all_" + userId,
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select id \"id\",pid \"pId\",name as \"name\",(case when (pid=0 or pid is null) then 'true' else 'false' end) \"open\" from  base_role ");
					}
				});
		renderJson(ajaxSucess(dept));
	}

	public void getDicById() {
		final Long id = getParaToLong("id");
		List<Record> dict = CacheKit.get(DICT_CACHE, "dict_" + id,
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select code from base_dict where id=?",id);
					}
				});
		renderJson(ajaxSucess(dict));
	}

	public void menuTreeList() {
		List<Record> menu = CacheKit.get(MENU_CACHE, "menu_tree_all",
				new IDataLoader() {
					@Override
					public List<Record> load() {
						return Db.find("select id as pkid,code \"id\",pCode \"pId\",name \"name\",(case when levels=1 then 'true' else 'false' end) \"open\" from base_menu where status=1 or status=2 order by levels asc,num asc");
					}
				});

		renderJson(ajaxSucess(menu));
	}

	public void menuTreeListByRoleId() {
		final String roleId = getPara("roleId", "0");
		List<Record> menu = CacheKit.get(MENU_CACHE, "tree_role_" + roleId,
				new IDataLoader() {
					@Override
					public Object load() {
						String table = "base_menu";
						String pid = "";
						List<Record> record = Db.find("select pid from base_role where id in (" + roleId + ")");
						for (Record p : record) {
							if (!Func.isEmpty(p.get("pid"))) {
								pid += p.get("pid").toString() + ",";
							}
						}
						if (!Func.isEmpty(pid)) {
							pid = JStrKit.removeSuffix(pid, ",");
							table = "(select * from base_menu where id in( select menuId from base_relation where roleId in ("
									+ pid + ") ))";
						}
						StringBuilder sb = new StringBuilder();
						sb.append("select m.id \"id\",(select id from base_menu  where code=m.pCode) \"pId\",name \"name\",(case when m.levels=1 then 'true' else 'false' end) \"open\",(case when r.menuId is not null then 'true' else 'false' end) \"checked\"");
						sb.append(" from ");
						sb.append(table);
						sb.append(" m left join (select menuId from base_relation where roleId in ("
								+ roleId
								+ ") group by menuId) r on m.id=r.menuId where m.status=1 or m.status=2 order by m.levels,m.num asc");
						return Db.find(sb.toString());
					}
				});

		renderJson(ajaxSucess(menu));
	}

	public void roleTreeListById() {
		final String Id = getPara("id");
		final String roleId = getPara("roleId", "0");
		List<Record> menu = CacheKit.get(ROLE_CACHE, "role_tree_" + Id,
				new IDataLoader() {
					@Override
					public List<Record> load() {
						String sql = "select id \"id\",pid \"pId\",name as \"name\",(case when (pid=0 or pid is null) then 'true' else 'false' end) \"open\" from  base_role order by pId,num asc";
						if (Id.indexOf(",") == -1) {
							sql = "select r.id \"id\",pid \"pId\",name as \"name\",(case when (pid=0 or pid is null) then 'true' else 'false' end) \"open\",(case when (r1.id=0 or r1.id is null) then 'false' else 'true' end) \"checked\" from  base_role r left join (select id  from base_role where id in ("
									+ roleId
									+ ")) r1 on r.id=r1.id order by pId,num asc";
						}
						return Db.find(sql);
					}
				});

		renderJson(ajaxSucess(menu));
	}
	
	public void getMenusByUserIdAndRoleId(){
		final String roleId = getPara("roleId", "0");
		final Long userId = getParaToLong("userId", 0L);
		List<BaseMenu> menu = CacheKit.get(MENU_CACHE, "menus_" + roleId+userId,
				new IDataLoader() {
					@Override
					public Object load() {
						return BusinessService.me.getMenusByUserIdAndRoleId(userId,roleId);
					}
				});
		renderJson(ajaxSucess(menu));
	}
	
	
	
	public void getcascadeListByPid() {
		String type = getPara(0);
		String source = getPara(1);
		String parameter = getPara(2);
		Map<String, String> mapparam = SqlKeyword.getSqlMapDeCode2(parameter);	
		SqlPara sqlPara = getSql(type,source,mapparam);
		List<Record> data = null;
		//如果是数据字典和区域则走缓存
		if("dict".equals(type)||"area".equals(type)){
			Object pid = mapparam.get("pid");
			data = CacheKit.get(DICT_CACHE, "cascade_"+type+"_"+pid,
					new IDataLoader() {
						@Override
						public List<Record> load() {
							return Db.find(sqlPara);
						}
					});
		}else{
			data = Db.find(sqlPara);
		}
		renderJson(ajaxSucess(data));
	}
	
	private SqlPara getSql(String type ,String source,Map<String, String> mapparam){
		SqlPara sqlPara = null;
		String sql = "";
		if (type.equals("dict")) {
			sql = "select num as code,id,pid,name from  base_dict where pid= #(pid)";
			sqlPara = Db.getSqlParaByString(sql, mapparam);
		} else if (type.equals("area")) {
			sql = "select CONCAT(id,'') as id,areaCode as code,pid,areaName as name from base_city where pid= #(pid) order by id";
			sqlPara = Db.getSqlParaByString(sql, mapparam);
		} else if (type.equals("diy")){
			sqlPara = Db.getSqlPara(source.replace("0x2E", "."),mapparam);
		}
		return sqlPara;
	}
}